package com.mflex.WHSmartWhouseAd.activity;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;


import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompatSideChannelService;

import com.mflex.WHSmartWhouseAd.R;
import com.mflex.WHSmartWhouseAd.adapter.FlexShelfOffOrderAdapter;
import com.mflex.WHSmartWhouseAd.adapter.FlexShelfOffOrderDetailAdapter;
import com.mflex.WHSmartWhouseAd.model.DoTransTaskInfo;
import com.mflex.WHSmartWhouseAd.model.FlexCarrierModel;
import com.mflex.WHSmartWhouseAd.model.M_WHSMTList;
import com.mflex.WHSmartWhouseAd.model.MaterialDetailModel;
import com.mflex.WHSmartWhouseAd.model.RequestModel;
import com.mflex.WHSmartWhouseAd.model.TaskFlexModel;
import com.mflex.WHSmartWhouseAd.model.TransTaskInfo;
import com.mflex.WHSmartWhouseAd.model.WHPKGLocData;
import com.mflex.WHSmartWhouseAd.utils.XToastUtils;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.net.JsonUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;

public class FlexShelfOffOrderDetailActivity extends AppCompatActivity {

    EditText stvSMTLot;
    EditText stvProduct;
    EditText stvFlexProduct;
    EditText stvFloor;
    EditText stvOrderQty;
    EditText stvZoom;
    EditText stvPlanQty;
    EditText stvScanQty;
    EditText stvVehicleNo;
    EditText stvCarNo;
    EditText stvPKGNo;
    EditText stvPKGType;
    EditText ScanPlateQty;
    EditText stvIsFeedingQty;
    ListView lvList;

    Button buttonClear;
    Button buttonSubmit;

    MiniLoadingDialog mMiniLoadingDialog;

    String userName;
    String userPassword;

    String TaskNo;
    //    FlexCarrierModel list;
    List<FlexCarrierModel> listdetail = new ArrayList<>();
    List<WHPKGLocData> PKGLists;

    List<WHPKGLocData> CommitPKGLists;

    private double scanQty;

    private String ShrinkType;

    List<String> scanList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_flex_shelf_off_order_detail);
        mMiniLoadingDialog = WidgetUtils.getMiniLoadingDialog(this, "加载...");

        stvSMTLot = findViewById(R.id.stvSMTLot);
        stvProduct = findViewById(R.id.stvProduct);
        stvFlexProduct = findViewById(R.id.stvFlexProduct);
        stvFloor = findViewById(R.id.stvFloor);

        stvOrderQty = findViewById(R.id.stvOrderQty);
        stvZoom = findViewById(R.id.stvZoom);
        stvPlanQty = findViewById(R.id.stvPlanQty);
        stvScanQty = findViewById(R.id.stvScanQty);

        stvVehicleNo = findViewById(R.id.stvVehicleNo);
        stvCarNo = findViewById(R.id.stvCarNo);
        stvPKGNo = findViewById(R.id.stvPKGNo);
        stvPKGType = findViewById(R.id.stvPKGType);

        ScanPlateQty = findViewById(R.id.ScanPlateQty);
        stvIsFeedingQty = findViewById(R.id.IsFeedingQty);

        lvList = findViewById(R.id.lvList);

        buttonClear = findViewById(R.id.button_clear);
        buttonSubmit = findViewById(R.id.button_submit);

        Intent intent = getIntent();

        userName = intent.getStringExtra("userName");
        TaskNo = intent.getStringExtra("TaskNo");
        userPassword = intent.getStringExtra("userPassword");

        stvOrderQty.setText(intent.getStringExtra("OrderQty"));
        stvSMTLot.setText(intent.getStringExtra("SMTLot"));
        stvFloor.setText(intent.getStringExtra("floor"));
        stvFlexProduct.setText(intent.getStringExtra("FLEXProduct"));
        stvProduct.setText(intent.getStringExtra("SMTProduct"));

        stvZoom.setText(intent.getStringExtra("ZoomScale"));
        stvPlanQty.setText(intent.getStringExtra("PlanQty"));
        stvIsFeedingQty.setText(intent.getStringExtra("IsFeedingQty"));

        ShrinkType = "";

        buttonClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Intent intent = new Intent(FlexShelfOffOrderDetailActivity.this, FlexShelfOffOrderActivity.class);
//                startActivity(intent);
                setResult(RESULT_OK);
                finish();
            }
        });
        buttonSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mMiniLoadingDialog.show();
                M_WHSMTList model = new M_WHSMTList(stvSMTLot.getText().toString(), stvVehicleNo.getText().toString(), userName, userPassword, CommitPKGLists,
                        TaskNo, stvOrderQty.getText().toString(), stvProduct.getText().toString(), stvPlanQty.getText().toString(), stvScanQty.getText().toString());
                RequestModel requestModel = new RequestModel();
                requestModel.setJson(JsonUtil.toJson(model));
                String json = JsonUtil.toJson(requestModel);
                System.out.println(json);
                XHttp.post("api/WHSmartWhousePDA/CommitFlexFeed")
                        .upJson(JsonUtil.toJson(requestModel))
                        .syncRequest(false)
                        .onMainThread(true)
                        .execute(new SimpleCallBack<Boolean>() {
                            @Override
                            public void onSuccess(Boolean response) {
                                mMiniLoadingDialog.dismiss();
                                XToastUtils.success("提交成功", 3000);
//                                单工单提交后自动带出该产品的下一个工单号，不需返回第二个页面进行工单选择
//                                Intent intent = new Intent(FlexShelfOffOrderDetailActivity.this, FlexShelfOffOrderActivity.class);
//                                startActivity(intent);
                                setResult(RESULT_OK);
                                finish();
                            }

                            @Override
                            public void onError(ApiException e) {
                                mMiniLoadingDialog.dismiss();
                                MediaPlayer mp = MediaPlayer.create(FlexShelfOffOrderDetailActivity.this, R.raw.error_voice);
                                mp.start();
                                new MaterialDialog.Builder(FlexShelfOffOrderDetailActivity.this)
                                        .iconRes(R.drawable.icon_warning)
                                        .title(R.string.tip_warning)
                                        .content(e.getMessage())
                                        .positiveText(R.string.lab_submit)
                                        .show();
                            }
                        });

            }
        });


        stvPKGNo.setOnKeyListener((view, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                mMiniLoadingDialog.show();
                if (StringUtils.equals("", stvPKGNo.getText().toString())) {
                    mMiniLoadingDialog.dismiss();
                    MediaPlayer mp = MediaPlayer.create(FlexShelfOffOrderDetailActivity.this, R.raw.error_voice);
                    mp.start();
                    XToastUtils.success("请先扫包号", 1500);
                    stvPKGNo.requestFocus();
                    return false;
                }
                if (StringUtils.equals("", stvCarNo.getText().toString())) {
                    mMiniLoadingDialog.dismiss();
                    MediaPlayer mp = MediaPlayer.create(FlexShelfOffOrderDetailActivity.this, R.raw.error_voice);
                    mp.start();
                    XToastUtils.success("请先扫车号", 1500);
                    stvCarNo.requestFocus();
                    return false;
                }
                if (StringUtils.equals("", stvVehicleNo.getText().toString())) {
                    mMiniLoadingDialog.dismiss();
                    MediaPlayer mp = MediaPlayer.create(FlexShelfOffOrderDetailActivity.this, R.raw.error_voice);
                    mp.start();
                    XToastUtils.success("请先扫载具号", 1500);
                    stvVehicleNo.requestFocus();
                    return false;
                }
                if (scanList.contains(stvPKGNo.getText().toString())) {
                    mMiniLoadingDialog.dismiss();
                    MediaPlayer mp = MediaPlayer.create(FlexShelfOffOrderDetailActivity.this, R.raw.error_voice);
                    mp.start();
                    XToastUtils.success("已扫描过该PKG/盘号", 1500);
                    stvPKGNo.setText("");
                    stvPKGNo.requestFocus();
                    return false;
                }
                String str1 = stvOrderQty.getText().toString();
                int num1 = Integer.parseInt(str1);

                if (!StringUtils.equals("", stvScanQty.getText().toString())) {

                    int num2 = (int) Math.round(Double.parseDouble(stvScanQty.getText().toString()));

                    if (num1 <= num2) {
                        mMiniLoadingDialog.dismiss();
                        MediaPlayer mp = MediaPlayer.create(FlexShelfOffOrderDetailActivity.this, R.raw.error_voice);
                        mp.start();
                        XToastUtils.success("已扫描数量不能大于计划数量", 1500);
                        stvVehicleNo.requestFocus();
                        return false;
                    }
                }

                String Type = "";

                if (stvPKGNo.getText().toString().contains("PKG")) {
                    Type = "PKG";
                } else {
                    Type = "Panel";
                }

                XHttp.get("api/WHSmartWhousePDA/GetScanPackageNumber2")
                        .params("TaskNo", TaskNo)
                        .params("PackageNumber", stvPKGNo.getText().toString())
                        .params("VehicleNumber", stvVehicleNo.getText().toString())
                        .params("CarNo", stvCarNo.getText().toString())
                        .params("Type", Type)
                        .syncRequest(false)
                        .onMainThread(true)
                        .timeOut(120000)
                        .execute(new SimpleCallBack<List<WHPKGLocData>>() {
                            @Override
                            public void onSuccess(List<WHPKGLocData> response) {
                                mMiniLoadingDialog.dismiss();
                                //判断涨缩值是否一致
                                if (StringUtils.isEmpty(ShrinkType)) {
                                    ShrinkType = response.get(0).getShrinkType();
                                } else if (!StringUtils.equals(ShrinkType, response.get(0).getShrinkType())) {
                                    MediaPlayer mp = MediaPlayer.create(FlexShelfOffOrderDetailActivity.this, R.raw.error_voice);
                                    mp.start();
                                    XToastUtils.success("涨缩值不一致，请检查", 1500);
                                    stvPKGNo.setText("");
                                    stvPKGNo.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            stvPKGNo.requestFocus();
                                        }
                                    }, 200);
                                    return;
                                }

//                                String type=response.get(0).getPKGProperties();//接口还没有给到
                                //BYPCS 不用输入数量
                                String type = "1";


                                stvPKGType.setText(type);
                                PKGLists = response;
                                if (CommitPKGLists != null && !CommitPKGLists.isEmpty()) {
                                    CommitPKGLists.addAll(PKGLists);
                                } else {
                                    CommitPKGLists = response;
                                }
                                if (listdetail != null && !listdetail.isEmpty()) {
                                    for (WHPKGLocData detail : PKGLists) {
                                        FlexCarrierModel list = new FlexCarrierModel();
                                        boolean flag = false;
                                        for (FlexCarrierModel listdetail : listdetail) {
                                            if (StringUtils.equals(listdetail.getPackageNumber(), detail.getPackNO()) && StringUtils.equals(listdetail.getFlexLot(), detail.getFlexLot())) {
                                                flag = true;
                                                String[] Qty = listdetail.getQty().split("/");
                                                Double GoodQty = Double.parseDouble(Qty[0]) + Double.parseDouble(detail.getGoodQty());
                                                Double DefectQty = Double.parseDouble(Qty[1]) + Double.parseDouble(detail.getDefectQty());
                                                listdetail.setQty(GoodQty + "/" + DefectQty);
                                            }
                                        }
                                        if (!flag) {
                                            list = new FlexCarrierModel();
                                            list.setCarrierName(detail.getVehicleNumber());
                                            list.setCarrierStatus(detail.getVehicleType());
                                            list.setFlexLot(detail.getFlexLot());
                                            list.setPackageNumber(detail.getPackNO());
                                            list.setZoomScale(detail.getShrinkType() == "" ? "" : detail.getShrinkType());
                                            String allQty = (detail.getGoodQty() + "/" + detail.getDefectQty()).toString();
                                            list.setQty(allQty);
                                            list.setExpireDate(detail.getEffectiveDate());
                                            listdetail.add(list);
                                        }
                                        scanQty = scanQty + Double.parseDouble(detail.getGoodQty());
                                    }
                                } else {
                                    for (WHPKGLocData detail : PKGLists) {
                                        FlexCarrierModel list = new FlexCarrierModel();
                                        list.setCarrierName(detail.getVehicleNumber());
                                        list.setCarrierStatus(detail.getVehicleType());
                                        list.setFlexLot(detail.getFlexLot());
                                        list.setPackageNumber(detail.getPackNO());
                                        list.setZoomScale(detail.getShrinkType() == "" ? "" : detail.getShrinkType());
                                        String allQty = (detail.getGoodQty() + "/" + detail.getDefectQty()).toString();
                                        list.setQty(allQty);
                                        list.setExpireDate(detail.getEffectiveDate());
                                        listdetail.add(list);
                                        scanQty = scanQty + Double.parseDouble(detail.getGoodQty());
                                    }
                                }

                                FlexShelfOffOrderDetailAdapter FlexShelfOffOrderDetailAdapter = new FlexShelfOffOrderDetailAdapter(FlexShelfOffOrderDetailActivity.this, listdetail);
                                lvList.setAdapter(FlexShelfOffOrderDetailAdapter);
                                stvScanQty.setText(String.valueOf(scanQty));

                                scanList.add(stvPKGNo.getText().toString());

                                if (StringUtils.equals("1", type)) {
                                    //BYPCS 不用输入数量
                                    ScanPlateQty.isEnabled();
                                    stvPKGNo.setText("");
                                    stvPKGNo.requestFocus();
                                } else {
                                    ScanPlateQty.isActivated();
                                    ScanPlateQty.requestFocus();
                                }
                            }

                            @Override
                            public void onError(ApiException e) {
                                mMiniLoadingDialog.dismiss();
                                stvPKGNo.setText("");
                                stvPKGNo.requestFocus();
                                MediaPlayer mp = MediaPlayer.create(FlexShelfOffOrderDetailActivity.this, R.raw.error_voice);
                                mp.start();
                                new MaterialDialog.Builder(view.getContext())
                                        .iconRes(R.drawable.icon_warning)
                                        .title(R.string.tip_warning)
                                        .content(Objects.requireNonNull(e.getMessage()))
                                        .positiveText(R.string.lab_submit)
                                        .show();
                            }
                        });
            }
            return false;
        });
        ScanPlateQty.setOnKeyListener((view, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                mMiniLoadingDialog.show();
                if (StringUtils.equals("", ScanPlateQty.getText().toString())) {
                    mMiniLoadingDialog.dismiss();
                    MediaPlayer mp = MediaPlayer.create(FlexShelfOffOrderDetailActivity.this, R.raw.error_voice);
                    mp.start();
                    XToastUtils.success("请修改成次品数量", 1500);
                    stvCarNo.requestFocus();
                    return false;
                }
                for (WHPKGLocData detail : PKGLists) {
                    FlexCarrierModel list = new FlexCarrierModel();
                    if (listdetail != null && !listdetail.isEmpty()) {
                        for (FlexCarrierModel listdetail : listdetail) {
                            if (StringUtils.equals(listdetail.getPackageNumber(), detail.getPackNO()) && StringUtils.equals(listdetail.getFlexLot(), detail.getFlexLot())) {
                                listdetail.setQty(ScanPlateQty.getText().toString());
                            }
                        }

                    }
                }
                FlexShelfOffOrderDetailAdapter FlexShelfOffOrderDetailAdapter = new FlexShelfOffOrderDetailAdapter(FlexShelfOffOrderDetailActivity.this, listdetail);
                lvList.setAdapter(FlexShelfOffOrderDetailAdapter);

            }
            return false;
        });
        stvCarNo.setOnKeyListener((view, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                mMiniLoadingDialog.show();
                if (StringUtils.equals("", stvCarNo.getText().toString())) {
                    mMiniLoadingDialog.dismiss();
                    MediaPlayer mp = MediaPlayer.create(FlexShelfOffOrderDetailActivity.this, R.raw.error_voice);
                    mp.start();
                    XToastUtils.success("请先扫车号", 1500);
                    stvCarNo.requestFocus();
                    return false;
                }
                XHttp.get("api/WHSmartWhousePDA/GetScanCarNumber")
                        .params("CarNumber", stvCarNo.getText().toString())
                        .syncRequest(false)
                        .onMainThread(true)
                        .timeOut(120000)
                        .execute(new SimpleCallBack<Boolean>() {
                            @Override
                            public void onSuccess(Boolean response) {
                                mMiniLoadingDialog.dismiss();
                                stvPKGNo.setText("");
                                stvPKGNo.requestFocus();
                            }

                            @Override
                            public void onError(ApiException e) {
                                mMiniLoadingDialog.dismiss();
                                stvCarNo.setText("");
                                stvCarNo.requestFocus();
                                MediaPlayer mp = MediaPlayer.create(FlexShelfOffOrderDetailActivity.this, R.raw.error_voice);
                                mp.start();
                                new MaterialDialog.Builder(view.getContext())
                                        .iconRes(R.drawable.icon_warning)
                                        .title(R.string.tip_warning)
                                        .content(Objects.requireNonNull(e.getMessage()))
                                        .positiveText(R.string.lab_submit)
                                        .show();
                            }
                        });
            }
            return false;
        });

        stvVehicleNo.setOnKeyListener((view, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                mMiniLoadingDialog.show();
                if (StringUtils.equals("", stvVehicleNo.getText().toString())) {
                    mMiniLoadingDialog.dismiss();
                    MediaPlayer mp = MediaPlayer.create(FlexShelfOffOrderDetailActivity.this, R.raw.error_voice);
                    mp.start();
                    XToastUtils.success("请先扫载具号", 1500);
                    stvVehicleNo.requestFocus();
                    return false;
                }
                XHttp.get("api/WHSmartWhousePDA/GetScanVehicleNumber")
                        .params("TaskNo", TaskNo)
                        .params("VehicleNumber", stvVehicleNo.getText().toString())
                        .syncRequest(false)
                        .onMainThread(true)
                        .timeOut(120000)
                        .execute(new SimpleCallBack<Boolean>() {
                            @Override
                            public void onSuccess(Boolean response) {
                                mMiniLoadingDialog.dismiss();

//                                PKGLists=response.getPKGList();
                            }

                            @Override
                            public void onError(ApiException e) {
                                mMiniLoadingDialog.dismiss();
                                stvVehicleNo.setText("");
                                stvVehicleNo.requestFocus();
                                MediaPlayer mp = MediaPlayer.create(FlexShelfOffOrderDetailActivity.this, R.raw.error_voice);
                                mp.start();
                                new MaterialDialog.Builder(view.getContext())
                                        .iconRes(R.drawable.icon_warning)
                                        .title(R.string.tip_warning)
                                        .content(Objects.requireNonNull(e.getMessage()))
                                        .positiveText(R.string.lab_submit)
                                        .show();
                            }
                        });
            }
            return false;
        });
    }
}